package com.example.wxsmart.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.wxsmart.dto.request.QuestionPageRequest;
import com.example.wxsmart.pojo.Question;
import com.example.wxsmart.resources.VideoResources;
import com.example.wxsmart.service.QuestionService;
import com.example.wxsmart.util.Result;
import com.example.wxsmart.util.excel.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Luojunxian
 * @data 2022/5/30 10:04
 * @classname QuestionController
 */
@Slf4j
@Api(tags = "问答curd")
@RestController
@RequestMapping("/question")
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private VideoResources videoResources;

    @PostMapping("/addOrUpdate")
    @ApiOperation("添加/修改")
    public Result<Boolean> addOrUpdate(@Validated @RequestBody Question question) {
        return Result.ok(questionService.addOrUpdate(question));
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除")
    public Result<Boolean> delete(@PathVariable("id") Integer questionId) {
        return Result.ok(questionService.delete(questionId));
    }

    @GetMapping("/list")
    @ApiOperation("分页查询")
    public Result<IPage<Question>> pageList(@Payload QuestionPageRequest request) {
        //videoResources.saveOrUpdateVideoQuestion();
        return Result.ok(questionService.getPagedList(request));
    }

    @PostMapping("/excelImport")
    @ApiOperation("问答导入")
    public Result<Boolean> excelImport(@RequestPart("file") MultipartFile file) throws Exception {
        log.info("Excel:开始导入...");
        List<Question> questionList = ExcelUtils.readMultipartFile(file, Question.class);
        log.info("Excel:导入成功,读取到 {} 行数据", questionList.size());
        return Result.ok(questionService.addOrUpdateList(questionList));
    }

    @GetMapping("/excelExport")
    @ApiOperation("问答导出")
    public void excelExport(HttpServletResponse response) {
        List<Question> list = questionService.list();
        log.info("Excel:开始导出...");
        ExcelUtils.export(response, "问答信息表", list, Question.class);
        log.info("Excel:导出成功");
    }


    @GetMapping("/test")
    @ApiOperation("测试")
    public void test() {
        questionService.test();
    }

}
